﻿///////////////////////////////////////////////////////////////////////////////
// File:        Mutex.hpp
// Author:      671643387@qq.com
// Description:
///////////////////////////////////////////////////////////////////////////////

#ifndef NIO_BASE_MUTEX_HPP_
#define NIO_BASE_MUTEX_HPP_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <boost/noncopyable.hpp>

#if defined(__WINDOWS__)
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#elif defined(__LINUX__)
#include <pthread.h>
#endif

namespace nio
{
    namespace base
    {
        class Mutex : public boost::noncopyable
        {
        public:
            Mutex(void)
            {
#if defined(__WINDOWS__)
                ::InitializeCriticalSection(&cs_);
#elif defined(__LINUX__)
                mutex_ = PTHREAD_MUTEX_INITIALIZER;
#endif
            }

            ~Mutex(void)
            {
#if defined(__WINDOWS__)
                ::DeleteCriticalSection(&cs_);
#elif defined(__LINUX__)
                ::pthread_mutex_destroy(&mutex_);
#endif
            }

            void lock(void)
            {
#if defined(__WINDOWS__)
                ::EnterCriticalSection(&cs_);
#elif defined(__LINUX__)
                ::pthread_mutex_lock(&mutex_);
#endif
            }

            void unlock(void)
            {
#if defined(__WINDOWS__)
                ::LeaveCriticalSection(&cs_);
#elif defined(__LINUX__)
                ::pthread_mutex_unlock(&mutex_);
#endif
            }

        private:
#if defined(__WINDOWS__)
            ::CRITICAL_SECTION cs_;
#elif defined(__LINUX__)
            ::pthread_mutex_t mutex_;
#endif
        };
    }
}

#endif //NIO_BASE_MUTEX_HPP_
